<template>
  <div class="app-container"  v-loading="treeLoading">
    <!-- 基础信息 -->
    <h5 class="titleInfo">添加角色</h5>
    <el-form class="form" ref="form"  label-width="130px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="部门名称">
            <el-select placeholder="请选择" v-model="form.deptId">
              <el-option
                v-for="item in dtoOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="角色名称">
            <el-input v-model="form.roleName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="所属系统">
        <Fromplatfrom @childfun="childfun" :values="0"></Fromplatfrom>
      </el-form-item>

      <el-row>
        <el-col :span="24">
          <!-- <el-form-item label="角色赋权">
                        <el-select
                            v-model="form.permissionIds"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            placeholder="请选择">
                            <el-option
                            v-for="item in permissOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
          </el-form-item>-->
          <el-form-item label="角色赋权">
            <el-tree
              style="margin-top:6px"
              :data="treeData"
              ref="rootTree"
              show-checkbox
              node-key="value"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button style="margin-top:30px" type="primary" @click="submitFn()">立即提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  listAdminRoles,
  listAdminPermissions,
  addAdminRole,
  listAllPermission
} from "@/api/roleManage";
import { listAdminDeptDTO } from "@/api/adminManage";
import Fromplatfrom from "../components/platform";
export default {
  name: "roleManageAdd",
  components: {
    Fromplatfrom
  },
  data() {
    return {
      treeLoading: true,
      value1: "",
      form: {
        deptId: null,
        roleName: "",
        subSys: 0,
        permissionIds: []
      },
      dtoOptions: [],
      listPage: {
        pageNum: 1,
        pageSize: 10
      },
      permissOptions: [],
      //角色赋权树
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  inject: ["reload"],
  created() {
    this.getDTO();
  },
  methods: {
    /**所属平台 */
    childfun(val) {
      console.log(val);
      this.form.subSys = val === "" ? -1 : val;
      this.abc();
    },
    // 角色赋权树
    getKeys() {
      var aKey = this.getCheckedKeys(
        this.treeData,
        this.$refs.rootTree.getCheckedKeys(),
        "value"
      );
      this.form.permissionIds = aKey;
      console.log(aKey);
    },
    getCheckedKeys(data, keys, key) {
      var res = [];
      recursion(data, false);
      return res;
      // arr -> 树形总数据
      // keys -> getCheckedKeys获取到的选中key值
      // isChild -> 用来判断是否是子节点
      function recursion(arr, isChild) {
        var aCheck = [];
        for (var i = 0; i < arr.length; i++) {
          var obj = arr[i];
          aCheck[i] = false;
          if (obj.children) {
            aCheck[i] = recursion(obj.children, true) ? true : aCheck[i];
            if (aCheck[i]) {
              res.push(obj[key]);
            }
          }
          for (var j = 0; j < keys.length; j++) {
            if (obj[key] == keys[j]) {
              aCheck[i] = true;
              if (res.indexOf(obj[key]) == -1) {
                res.push(obj[key]);
              }
              break;
            }
          }
        }
        if (isChild) {
          return aCheck.indexOf(true) != -1;
        }
      }
    },
    //获取下拉部门列表
    getDTO() {
      listAdminDeptDTO().then(res => {
        let resData = res.data.data;
        let newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id,
            label: e.deptName
          });
        });
        this.dtoOptions = newData;
      });
      this.abc();
    },
    abc() {
      //获取权限列表
      listAllPermission({ subSys: this.form.subSys }).then(res => {
        let resData = res.data.data;
        let newData = [];
        resData.forEach((e1, index1) => {
          newData.push({
            value: e1.id,
            label: e1.name
          });
          if (e1.children.length > 0) {
            newData[index1]["children"] = [];
            e1.children.forEach((e2, index2) => {
              newData[index1]["children"].push({
                value: e2.id,
                label: e2.name
              });
              if (e2.children.length > 0) {
                newData[index1]["children"][index2]["children"] = [];
                e2.children.forEach((e3, index3) => {
                  newData[index1]["children"][index2]["children"].push({
                    value: e3.id,
                    label: e3.name
                  });
                  if (e3.children.length > 0) {
                    newData[index1]["children"][index2]["children"][index3][
                      "children"
                    ] = [];
                    e3.children.forEach((e4, index4) => {
                      newData[index1]["children"][index2]["children"][index3][
                        "children"
                      ].push({
                        value: e4.id,
                        label: e4.name
                      });
                    });
                  }
                });
              }
            });
          }
        });
        this.treeLoading = false;
        this.treeData = newData;
      });
    },
    //提交
    submitFn() {
      if (this.form.subSys == -1) {
        this.$message({
          showClose: true,
          message: "系统必须选择",
          type: "warning"
        });
        return;
      }
      this.getKeys();
      let datas = this.form;
      console.log(datas);
      addAdminRole(this.form).then(res => {
        if (!res.data.code) {
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success"
          });
          this.$router.push("/roleManageIndex");
          this.reload();
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "warning"
          });
        }
      });
    }
  }
};
</script>
<style scoped>
.app-container {
  padding: 0.1px !important;
}
</style>
